import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { networkStatus } from '../utils/networkStatus';

// 默认服务器URL
const DEFAULT_WEBSOCKET_URL = 'ws://localhost:1234';

// 离线存储适配器
class OfflineStorage {
  constructor(docId) {
    this.storageKey = `yjs-offline-${docId}`;
  }

  save(ydoc) {
    const update = Y.encodeStateAsUpdate(ydoc);
    localStorage.setItem(this.storageKey, JSON.stringify(Array.from(update)));
  }

  load(ydoc) {
    const saved = localStorage.getItem(this.storageKey);
    if (saved) {
      const update = new Uint8Array(JSON.parse(saved));
      Y.applyUpdate(ydoc, update);
      return true;
    }
    return false;
  }

  clear() {
    localStorage.removeItem(this.storageKey);
  }
}

export const setupYjs = (documentId, websocketUrl = DEFAULT_WEBSOCKET_URL, username = null) => {
  // 创建新的Yjs文档
  const ydoc = new Y.Doc();
  const offlineStorage = new OfflineStorage(documentId);
  
  // 尝试加载离线数据
  offlineStorage.load(ydoc);
  
  // 创建共享的canvas数据结构
  const ycanvas = ydoc.getMap('canvas');
  
  // 连接到WebSocket服务器
  const provider = new WebsocketProvider(websocketUrl, documentId, ydoc, {
    disableBc: true, // 禁用广播通道
    connect: networkStatus.isOnline() // 根据网络状态决定是否立即连接
  });
  
  // 监听网络状态变化
  const removeNetworkListener = networkStatus.addListener((isOnline) => {
    if (isOnline) {
      provider.connect();
      // 网络恢复时保存当前状态
      offlineStorage.save(ydoc);
      offlineStorage.clear();
    } else {
      provider.disconnect();
    }
  });

  // 设置用户信息
  if (username) {
    provider.awareness.setLocalStateField('user', {
      name: username,
      color: getRandomColor(),
    });
  }

  // 添加文档变更监听器，离线时保存变更
  ydoc.on('update', () => {
    if (!networkStatus.isOnline()) {
      offlineStorage.save(ydoc);
    }
  });

  return {
    ydoc,
    ycanvas,
    provider,
    awareness: provider.awareness,
    destroy: () => {
      removeNetworkListener();
      provider.destroy();
    }
  };
};

// 生成随机颜色供用户识别
const getRandomColor = () => {
  const colors = [
    '#f44336', '#e91e63', '#9c27b0', '#673ab7', 
    '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4',
    '#009688', '#4caf50', '#8bc34a', '#cddc39'
  ];
  return colors[Math.floor(Math.random() * colors.length)];
};

// 导出离线存储适配器
export { OfflineStorage };